/*
 ** address check 详细地址校验
 **
 ** 校验规则：
 ** 1、除""、"#"、"-"外不允许有其他特殊字符输入
 ** 2、长度为200为字符
 **
 */
(function() {
    'use strict';

    angular
        .module('elife')
        .directive('addressCheck', addressCheck);
    addressCheck.$inject = ['VALIDATION'];

    function addressCheck(VALIDATION) {
        var directive = {
            restrict: 'A',
            require: 'ngModel',
            link: linkFunc
        };
        return directive;

        function linkFunc(scope, elem, attr, ngModel) {
            scope.$watch(attr.ngModel, function(value) {
                var typeArray = ['invalid', 'length', 'number'];

                function setValidity(type) {
                    for (var i = 0; i < typeArray.length; i++) {
                        ngModel.$setValidity(typeArray[i], true);
                    }

                    if (type && typeArray.indexOf(type) != -1) {
                        ngModel.$setValidity(type, false);
                    }
                }

                if (!value) {
                    setValidity();
                    return;
                }

                // 除""、"#"、"-"外不允许有其他特殊字符输入
                if (!VALIDATION.addressCheck(value)) {
                    setValidity('invalid');
                    return;
                }

                // 长度校验
                if (VALIDATION.stringLengthCheck(value, 4, 'lt') || VALIDATION.stringLengthCheck(value, 50, 'gt')) {
                    setValidity('length');
                    return;
                }

                // 数字校验
                if (!VALIDATION.numberCheck(value)) {
                    setValidity('number');
                    return;
                }

                setValidity();
            });
        }
    }
})();
